using DocumentFormat.OpenXml.EMMA;
using MediatR;
using ProduceBasicData.Api.Application.Command.ProductionManage.Repost;
using ProduceBasicData.Domain.FactoryModeling;
using ProduceBasicData.Domain.ProductionManage;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.ProductionManage.Repost
{
    public class ApproveReportCommandHandler : IRequestHandler<ApproveReportCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<Production_report> _production_report;
        private readonly IBaseRespository<Work_order> _work_order;
        private readonly IBaseRespository<Report_approval> _report_approval;
        private readonly IBaseRespository<Report_Record> _report_record;
        private readonly IBaseRespository<WorkShopOrder> _shoporderRepository;
        public ApproveReportCommandHandler(
            IBaseRespository<Production_report> production_report,
            IBaseRespository<Work_order> work_order,
            IBaseRespository<Report_approval> report_approval,
            IBaseRespository<Report_Record> report_record,
            IBaseRespository<WorkShopOrder> shoporderRepository)
        {
            _production_report = production_report;
            _work_order = work_order;
            _report_approval = report_approval;
            _report_record = report_record;
            _shoporderRepository = shoporderRepository;
        }

        public async Task<ApiResult<int>> Handle(ApproveReportCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>()
            {
                Code = ApiEnum.Success,
                Msg = "审批操作成功"
            };

            try
            {
                DateTime time = DateTime.Now;
                using (var transaction = await _production_report.DB.Database.BeginTransactionAsync(cancellationToken))
                {
                    // 获取报工信息
                    var productionReport = await _production_report.GetModelAsync(request.Report_id);
                    if (productionReport == null)
                    {
                        result.Code = ApiEnum.Failed;
                        result.Msg = "报工记录不存在";
                        return result;
                    }

                    // 获取工单信息
                    var workOrder = await _work_order.GetModelAsync(productionReport.Order_id);
                    if (workOrder == null)
                    {
                        result.Code = ApiEnum.Failed;
                        result.Msg = "工单不存在";
                        return result;
                    }

                    // 更新报工审核记录
                    var reportApproval = _report_approval.GetAll()
                        .FirstOrDefault(ra => ra.Report_id == request.Report_id);
                    
                    if (reportApproval != null)
                    {
                        reportApproval.Approval_id = request.Approval_id;
                        reportApproval.Approval_status = request.Approval_status;
                        reportApproval.Approval_date = time;
                        reportApproval.Comments = request.Comments;
                        reportApproval.UpdateName = request.UpdateName;
                        reportApproval.UpdateTime = time;
                        await _report_approval.Update(reportApproval);
                    }

                    // 根据审批状态更新报工和工单状态
                    if (request.Approval_status == 2) // 2通过
                    {
                        // 更新报工状态为3已完成
                        productionReport.Report_status = 3;
                        productionReport.UpdateName = request.UpdateName;
                        productionReport.UpdateTime = time;
                        await _production_report.Update(productionReport);

                        // 更新工单状态为3已下发
                        workOrder.Status = 3;
                        workOrder.UpdateName = request.UpdateName;
                        workOrder.UpdateTime = time;
                        await _work_order.Update(workOrder);

                        // 更新报工记录状态为2已确认
                        var reportRecord = _report_record.GetAll()
                            .FirstOrDefault(rr => rr.Task_id == request.Report_id);
                        if (reportRecord != null)
                        {
                            reportRecord.Report_Status = 2;
                            reportRecord.UpdateName = request.UpdateName;
                            reportRecord.UpdateTime = time;
                            await _report_record.Update(reportRecord);
                        }
                        //工单状态已下发时,工单数据通过车间工单中间表传给车间
                        var shoporder = new WorkShopOrder()
                        {
                            WorkorderId = workOrder.Id,
                            WorkshopId = workOrder.WorkshopId,
                        };
                        await _shoporderRepository.AddAsync(shoporder);

                        result.Msg = "审批通过，报工和工单状态已更新";
                    }
                    else if (request.Approval_status == 3) // 3驳回
                    {
                        // 更新报工状态为1已提交（重新提交）
                        productionReport.Report_status = 1;
                        productionReport.UpdateName = request.UpdateName;
                        productionReport.UpdateTime = time;
                        await _production_report.Update(productionReport);

                       // 工单状态保持为2待审核
                         workOrder.Status = 2; // 保持待审核状态

                        // 更新报工记录状态为1待审核
                        var reportRecord = _report_record.GetAll()
                            .FirstOrDefault(rr => rr.Task_id == request.Report_id);
                        if (reportRecord != null)
                        {
                            reportRecord.Report_Status = 1;
                            reportRecord.UpdateName = request.UpdateName;
                            reportRecord.UpdateTime = time;
                            await _report_record.Update(reportRecord);
                        }
                        result.Msg = "审批驳回，报工状态已重置为待提交";
                    }
                    reportApproval.Approval_id = 0;
                    await _report_approval.Update(reportApproval);
                    // 提交事务
                    await transaction.CommitAsync(cancellationToken);
                    result.Data = request.Report_id;
                }
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Failed;
                result.Msg = $"审批操作失败：{ex.Message}";
            }

            return result;
        }
    }
}
